package edu.hunau.cxb18.orm.handler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author hb
 * @create 2020-02-26 16:52
 */
public class BooleanTypeHandler implements TypeHandler<Boolean> {

    /** 获得结果集中的结果如果是1返回true,否则返回false */
    public Boolean getResult(ResultSet rs, String column) throws SQLException {
        String str = rs.getString(column);
        Boolean rt = Boolean.FALSE;
        if (str.equalsIgnoreCase("1")) {
            rt = Boolean.TRUE;
        }
        return rt;
    }

    /*用于在Mybatis获取数据结果集时如何把数据库类型转换为对应的Java类型*/
    public Boolean getResult(ResultSet rs, int index) throws SQLException {
        String str = rs.getString(index);
        Boolean rt = Boolean.FALSE;
        if (str.equalsIgnoreCase("1")) {
            rt = Boolean.TRUE;
        }
        return rt;
    }
    /* 用于Mybatis在调用存储过程后把数据库类型的数据转换为对应的Java类型*/
    @Override
    public Boolean getResult(CallableStatement rs, int index) throws SQLException {
        String str = rs.getString(index);
        Boolean rt = Boolean.FALSE;
        if (str.equalsIgnoreCase("1")) {
            rt = Boolean.TRUE;
        }
        return rt;
    }



    /* 用于定义在Mybatis设置参数时该如何把Java类型的参数转换为对应的数据库类型  */
    public void setParameter(PreparedStatement pstm, int index, Boolean value,
                             JdbcType type) throws SQLException {
        String data = value == true ? "1" : "0";
        pstm.setString(index, data);
    }
}
